package a66weding.com.jiehuntong.activity.me;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.model.DateModel;
import a66weding.com.jiehuntong.widgets.wheelview.OnWheelChangedListener;
import a66weding.com.jiehuntong.widgets.wheelview.WheelView;
import a66weding.com.jiehuntong.widgets.wheelview.adapters.ArrayWheelAdapter;
import a66weding.com.jiehuntong.widgets.wheelview.adapters.NumericWheelAdapter;

/**
 * 这是我的-设置年龄的Activity
 * Created by Administrator on 2016/7/19.
 */
public class MeSetAgeActivity extends Activity implements View.OnClickListener,OnWheelChangedListener , OnNetResultListener {
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private TextView mCancel;
    private TextView mConfim;
    private List<Map<String,String[]>> mDateList;
    private String mCurrentProviceName;
    private String mCurrentCityName;
    private DateModel mDate;
    private String mYear;
    private String mMonth;
    private String mDay;
    private static  final int  SUCESS=1;
    private String[] mYears;
    private String[] mDays;
    private int mStartYear=1849;
    private int mCurrentYear;
    private int mSelectYear;
    private int mCurrentMonth;
    private int mSelectDay;
    private int year;
    private int month;
    private int day;
    private int age;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pop_tools_holiday_bir_date);
        setUpViews();
        setUpListener();
        setUpData();
    }
    private void setUpViews() {
        mViewProvince = (WheelView) findViewById(R.id.id_province);
        mViewCity = (WheelView) findViewById(R.id.id_city);
        mViewDistrict = (WheelView) findViewById(R.id.id_district);
        mCancel = (TextView) findViewById(R.id.tv_cancel);
        mConfim = (TextView) findViewById(R.id.tv_confim);
    }
    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件
        mCancel.setOnClickListener(this);
        mConfim.setOnClickListener(this);
    }
    private void setUpData() {
        getTime();
        mYears = new String[121];
        for (int i = 0; i < 120; i++) {
            mYears[i]=1980+i+"年";
        }
        mDays = new String [30];
        for (int i = 0; i < 30; i++) {
            mDays[i]=i+1+"日";
        }
        if(mDays ==null) {
            mDays =new String[]{""};
        }
        NumericWheelAdapter yearWheelAdapter = new NumericWheelAdapter(this, mStartYear, 2100);
        NumericWheelAdapter monthWheelAdapter = new NumericWheelAdapter(this, 1, 12);
        mViewProvince.setViewAdapter(yearWheelAdapter);
        mViewCity.setViewAdapter(monthWheelAdapter);
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        int index = mCurrentYear - mStartYear;
        mViewProvince.setCurrentItem(index);
        mViewCity.setCurrentItem(mCurrentMonth);
        mViewCity.setCyclic(true);
        updateDays();
    }

    private void updateDays() {
        year=mViewProvince.getCurrentItem()+mStartYear;
        month=mViewCity.getCurrentItem()+1;
        String [] mDays=null;
        int lastDay=30;
        if(month==2) {
            if(isLeapYear(year)) {
                mDays=new String [29];
                for (int i = 1; i < 29; i++) {
                    mDays[i]=i+"日";
                }
                lastDay=29;
            }else{
                mDays=new String [28];
                for (int i = 1; i < 28; i++) {
                    mDays[i]=i+"日";
                }
                lastDay=28;
            }
        }else if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
            mDays=new String [31];
            for (int i = 1; i < 31; i++) {
                mDays[i]=i+"日";
            }
            lastDay=31;
        }else{
            mDays=new String [30];
            for (int i = 1; i < 30; i++) {
                mDays[i]=i+"日";
            }
            lastDay=30;
        }
        if(mDays==null) {
            mDays=new String[]{""};
        }
        NumericWheelAdapter dayWheelAdapter = new NumericWheelAdapter(this, 1, lastDay);
        mViewDistrict.setViewAdapter(dayWheelAdapter);
        mViewDistrict.setVisibleItems(7);
        if(mSelectDay>mDays.length-1) {
            mSelectDay=mDays.length-1;
        }
        mViewDistrict.setCurrentItem(mSelectDay);
        mViewDistrict.setCyclic(true);
    }


    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SUCESS:
                    mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(MeSetAgeActivity.this, mDate.mProvinceDatas));
                    // 设置可见条目数量
                    mViewProvince.setVisibleItems(7);
                    mViewCity.setVisibleItems(7);
                    mViewDistrict.setVisibleItems(7);
                    updateCities();
                    updateAreas();
                    break;
            }

        }
    };

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mDate.mProvinceDatas[pCurrent];
        String[] cities = mDate.mMonth;
        if (cities == null) {
            cities = new String[] { "3月" };
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(7);
        updateAreas();
    }
    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        int yCurrent=  mViewProvince.getCurrentItem();
        Map<String, String[]> stringMap = mDateList.get(yCurrent);
        String[] areas = stringMap.get(mDate.mMonth[pCurrent]);
        if (areas == null) {
            areas = new String[] { "6日" };
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
        mViewDistrict.setCurrentItem(mSelectDay);

    }
    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if(wheel==mViewProvince ){
            mSelectYear=newValue;

            if((mStartYear+mSelectYear) > mCurrentYear) {
                mViewProvince.setCurrentItem(mCurrentYear - mStartYear);
            }
            updateDays();
        }else if( wheel==mViewCity) {
            updateDays();
        }else if(wheel == mViewDistrict){
            mSelectDay=newValue;
        }
        day = mSelectDay + 1;
    }


    public static boolean isLeapYear(int year) {
        boolean flag=false;
        if((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))){
            flag=true;
        }
        return flag;
    }

    public void getTime(){
        Calendar c = Calendar.getInstance();
//        取得系统日期:
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
    }







    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_cancel:    //点击取消,关闭界面
                finish();
                break;
            case R.id.tv_confim:
                Toast.makeText(MeSetAgeActivity.this, year + "年"+ month +"月"+ day +"日", Toast.LENGTH_SHORT).show();
                age = mCurrentYear - year;

                String url= UrlDealUtil.getRealUrl(RequestCode.UPDATE_CUSTOMERBIRTHDAY);
                HashMap<String,String> requestParams=new HashMap<String,String>();
                requestParams.put("Birthday",""+age);
                HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                        this, CommonResultBean.class, RequestCode.UPDATE_CUSTOMERBIRTHDAY, requestParams);
                HttpHandleUtil.executeCommonPost(this,httpRequestBean);

                break;
        }
    }


    @Override
    public void onSucess(SuccessBean sucessbean) {
        //更新内存
        DataWareHourse.getInstance().getmUser().getData().get(0).setNvc_Age("" + age);
        //更新本地缓存
        CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, DataWareHourse.getInstance().getmUser());
        Toast.makeText(this,"设置年龄成功",Toast.LENGTH_SHORT).show();

        finish();
    }

    @Override
    public void onError(ErrorBean errorBean) {
        Toast.makeText(this,"年龄设置失败,请稍后再试",Toast.LENGTH_SHORT).show();
    }


}
